package com.example.demo.algorithm.lesson.basic.class2;

import java.util.Stack;

/**
 * @author Administrator
 * @date 2020/4/26
 */
public class GetMinStack {
    public static class MyStack1 {
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> helper = new Stack<>();

        public void push(Integer value) {
            if (stack.isEmpty()) {
                helper.push(value);
            } else if (getMin() > value) {
                helper.push(value);
            } else {
                helper.push(getMin());
            }
            stack.push(value);
        }

        public Integer pop() {
            if (stack.isEmpty()) {
                throw new RuntimeException("Empty Stack!");
            }
            helper.pop();
            return stack.pop();
        }

        public Integer getMin() {
            if (stack.isEmpty()) {
                throw new RuntimeException("Empty Stack!");
            }
            return helper.peek();
        }
    }

    public static class MyStack2 {
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> helper = new Stack<>();

        public void push(Integer value) {
            if (stack.isEmpty()) {
                helper.push(value);
            } else if (getMin() >= value) {
                helper.push(value);
            }
            stack.push(value);
        }

        public Integer pop() {
            if (stack.isEmpty()) {
                throw new RuntimeException("Empty Stack!");
            }
            Integer pop = stack.pop();
            if (pop.equals(getMin())) {
                helper.pop();
            }
            return pop;
        }

        public Integer getMin() {
            if (stack.isEmpty()) {
                throw new RuntimeException("Empty Stack!");
            }
            return helper.peek();
        }
    }

    public static void main(String[] args) {
        MyStack1 stack1 = new MyStack1();
        stack1.push(3);
        System.out.println(stack1.getMin());
        stack1.push(4);
        System.out.println(stack1.getMin());
        stack1.push(1);
        System.out.println(stack1.getMin());
        System.out.println(stack1.pop());
        System.out.println(stack1.getMin());

        System.out.println("=============");

        MyStack1 stack2 = new MyStack1();
        stack2.push(3);
        System.out.println(stack2.getMin());
        stack2.push(4);
        System.out.println(stack2.getMin());
        stack2.push(1);
        System.out.println(stack2.getMin());
        System.out.println(stack2.pop());
        System.out.println(stack2.getMin());
    }
}
